using System;
using System.Collections;
using System.Web.UI.WebControls;

namespace nToolbox.Web.Controls
{
    public class DropDownListBinder
    {
        private readonly IEnumerable _DataSource;
        private readonly DropDownList _Ddl;
        private ListItem _FirstItem;
        private string _DefaultValue;
        private string _DefaultText;
        private string _PropertyAsDataValue;
        private string _PropertyAsTextValue;

        public DropDownListBinder(IEnumerable dataSource, DropDownList ddl)
        {
            _DataSource = dataSource;
            _Ddl = ddl;
        }

        public DropDownListBinder InsertingAsFirstItem(string topItemValue, string topItemText)
        {
            _FirstItem = new ListItem(topItemText, topItemValue);
            return this;
        }

        public DropDownListBinder AutoSelectItemWithValueOf(string defaultValue)
        {
            _DefaultValue = defaultValue;
            return this;
        }

        public DropDownListBinder AutoSelectItemWithTextOf(string defaultText)
        {
            _DefaultText = defaultText;
            return this;
        }

        public DropDownListBinder UsePropertyForDataValue(string propertyAsDataValue)
        {
            _PropertyAsDataValue = propertyAsDataValue;
            return this;
        }

        public DropDownListBinder UsePropertyForTextValue(string propertyAsTextValue)
        {
            _PropertyAsTextValue = propertyAsTextValue;
            return this;
        }

        public void Do()
        {
            _Ddl.DataSource = _DataSource;
            if (!string.IsNullOrEmpty(_PropertyAsDataValue)) _Ddl.DataValueField = _PropertyAsDataValue;
            if (!string.IsNullOrEmpty(_PropertyAsTextValue)) _Ddl.DataTextField= _PropertyAsTextValue;
            _Ddl.DataBind();
            _Ddl.Items.Insert(0, _FirstItem);

            foreach (ListItem listItem in _Ddl.Items)
            {
                if(!string.IsNullOrEmpty(_DefaultValue))
                {
                    listItem.Selected = listItem.Value.Equals(_DefaultValue, StringComparison.CurrentCultureIgnoreCase);
                }
                else if (!string.IsNullOrEmpty(_DefaultText))
                {
                    listItem.Selected = listItem.Text.Equals(_DefaultText, StringComparison.CurrentCultureIgnoreCase);
                }
            }
        }
    }
}